<template>
  <view class="page">
    <!-- 消息列表 -->
    <scroll-view class="message-list" scroll-y lower-threshold="60" @scrolltolower="loadMore">
      <view class="message-item" v-for="msg in messageList" :key="msg.id" @click="goToDetail(msg)">
        <view class="message-icon" :class="'type-' + msg.type">
          <text class="icon-emoji">{{ getTypeIcon(msg.type) }}</text>
        </view>
        <view class="message-content">
          <view class="message-header">
            <text class="message-title">{{ msg.title }}</text>
            <text class="message-time">{{ msg.time }}</text>
          </view>
          <text class="message-desc">{{ msg.content }}</text>
        </view>
        <view class="message-badge" v-if="!msg.read"></view>
      </view>

      <!-- 空状态 -->
      <view class="empty" v-if="messageList.length === 0">
        <image class="empty-image" src="/static/images/empty-product.png" mode="aspectFit"></image>
        <text class="empty-text">暂无消息</text>
      </view>

      <!-- 加载更多 -->
      <view class="loadmore" v-if="messageList.length > 0">
        <text class="loadmore-text">{{ loadingText }}</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getMessages, markMessageRead } from '@/api/message'
export default {
  data() {
    return {
      messageList: [],
      page: 1,
      pageSize: 20,
      loading: false,
      finished: false
    }
  },
  computed: {
    loadingText() {
      if (this.loading) return '加载中...'
      if (this.finished) return '没有更多了'
      return '上拉加载更多'
    }
  },
  onLoad() {
    this.loadMessages()
  },
  onShow() {
    this.refreshBadge()
  },
  onPullDownRefresh() {
    this.page = 1
    this.finished = false
    this.loadMessages(true)
  },
  methods: {
    async loadMessages(fromPullDown = false) {
      if (this.loading || this.finished) return
      this.loading = true
      try {
        const pageData = await getMessages({ pageNum: this.page, pageSize: this.pageSize })
        const rawRecords = Array.isArray(pageData.records) ? pageData.records : []
        const mapped = rawRecords.map(r => ({
          id: r.id,
          type: r.type,
          title: r.title,
          content: r.content,
          time: r.createTime,
          read: r.readStatus === 1,
          bizType: r.bizType,
          bizId: r.bizId
        }))
        if (this.page === 1) this.messageList = mapped
        else this.messageList = this.messageList.concat(mapped)
        if (rawRecords.length < this.pageSize) this.finished = true
      } catch (e) {
      } finally {
        this.loading = false
        if (fromPullDown) {
          setTimeout(() => { uni.stopPullDownRefresh() }, 300)
        }
      }
    },
    loadMore() {
      if (this.loading || this.finished) return
      this.page++
      this.loadMessages()
    },
    getTypeIcon(type) {
      const icons = { 1: '📦', 2: '🔔', 3: '🎉', 4: '📢' }
      return icons[type] || '💬'
    },
    async goToDetail(msg) {
      try {
        if (!msg.read) {
          await markMessageRead(msg.id)
          msg.read = true
          // 同步更新全局用户未读数并刷新角标
          this.$store.commit('DECREMENT_USER_UNREAD_COUNT', 1)
          this.refreshBadge()
        }
      } catch (e) {}
      if (msg.bizType === 'order' && msg.bizId) {
        uni.navigateTo({ url: `/pages/order/detail?id=${msg.bizId}` })
      } else if (msg.bizType === 'feedback' && msg.bizId) {
        uni.navigateTo({ url: `/pages/feedback/detail?id=${msg.bizId}` })
      } else {
        uni.showToast({ title: '暂无详情', icon: 'none' })
      }
    },
    async refreshBadge() {
      try {
        // 直接使用 store 中的用户未读数，不再请求接口
        const count = Number(this.$store.state.userUnreadCount) || 0
        if (count > 0) {
          uni.setTabBarBadge({ index: 2, text: String(count > 99 ? 99 : count) })
        } else {
          uni.removeTabBarBadge({ index: 2 })
          uni.hideTabBarRedDot({ index: 2 })
        }
      } catch (e) {
        uni.hideTabBarRedDot({ index: 2 })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f7fa;
}

.message-list {
  height: 100vh;
}

.message-item {
  background: #fff;
  padding: 24rpx 20rpx;
  display: flex;
  gap: 20rpx;
  align-items: center;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;
  
  &:active {
    background: #f8f8f8;
  }
}

.message-icon {
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  
  &.type-1 {
    background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%);
  }
  
  &.type-2 {
    background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
  }
  
  &.type-3 {
    background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  }
  
  &.type-4 {
    background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  }
  
  .icon-emoji {
    font-size: 48rpx;
  }
}

.message-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  min-width: 0;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16rpx;
}

.message-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.message-time {
  font-size: 24rpx;
  color: #999;
  flex-shrink: 0;
}

.message-desc {
  font-size: 26rpx;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.message-badge {
  position: absolute;
  top: 24rpx;
  right: 20rpx;
  width: 16rpx;
  height: 16rpx;
  background: #ff4d4f;
  border-radius: 50%;
}

/* 空状态 */
.empty {
  padding: 120rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 32rpx;
  
  .empty-image {
    width: 400rpx;
    height: 300rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

/* 加载更多 */
.loadmore {
  padding: 40rpx 20rpx;
  text-align: center;
  
  .loadmore-text {
    font-size: 24rpx;
    color: #999;
  }
}
</style>

